/**
 * Created by liyun
 * 
 * 微信开放平台接口
 * 
 */

'use strict';

var express = require('express');
var router = express.Router();
const oauth = require('wechat-oauth');
const settings = require('../config/settings');
const logger = require('log4js').getLogger("openWX");
const redis = require("redis");
const users = require('../models/users');
const log = require('log4js').getLogger("users");
const luosimao = require('../lib/luosimao');
const randomstring = require('randomstring');
const redisClient = require('../lib/redisClient');
const utils = require('../lib/utils');

/**************************************************************************************************************
 *   redis init  auth token select 0
 */
var redis_client = redis.createClient(settings.redis_conf.port, settings.redis_conf.host);

redis_client.on('ready', function(){
    redis_client.select(0);     // 0
});

redis_client.on('error', function(err){
    logger.error('oauth >> redis_client: ' + err);
});

/**************************************************************************************************************
 * 网页登录，取得转换网址，及openid
 */
var client = new oauth(settings.weixinOpen.AppID, settings.weixinOpen.AppSecret, function(openid, callback){
    // get the token by openid
    redis_client.hget('wxOpenAuthToken', openid, function(err, result){
        if (err) logger.error('oauth >> redis_client:' + err);
        callback(null, JSON.parse(result));
    })

}, function(openid, token, callback){
    // set hash key wxOpenAuthToken
    redis_client.hset('wxOpenAuthToken', openid, JSON.stringify(token), function(err){
        if (err) {
            logger.error('oauth >> redis_client >> set wxOpenAuthToken : ' + err);
            return callback(err);
        }else{
            callback(null);  // err is null
        }
    });
});

/**
 *   获取用户openid
 */
router.get('/getOpenId', function(req, res){
    //微信登录插件返回的code
    var code = req.query.code;
    client.getAccessToken(code, function(err, result){
        if (err){
            res.send({error: err});
        }else{
            res.send({openid: result.data.openid});
        }
    });

});

/**
 *   获取用户信息
 */
router.get('/getUser', function(req, res){
    var openid = req.query.openid;
    client.getUser({openid: openid, lang: 'zh_CN'}, function(err, data){
        logger.error(err);
        res.send({err: err, data: data});
    });
});


/**
 *   获取用户信息
 */
router.get('/getUserInfo', function(req, res){
    var code = req.query.code;
    client.getAccessToken(code, function(err, result){ //根据code获取用户openid
        if (err){
            logger.error(err);
            res.send({success: false, error: err});
        }else{
            client.getUser({openid: result.data.openid, lang: 'zh_CN'}, function(err, data){ //根据openid获取微信用户信息
                if(err){
                    logger.debug(err);
                    return res.send({success: false, error: err});
                }
                logger.debug(data);
                users.get_user_openid(data.unionid, function (err, user) { //从本地数据库查询是否已经注册
                    if(err){
                        logger.debug(err);
                        return res.send({success: false, error: err});
                    }
                    if(user.rowCount == 0){
                        res.send({success: true, signin: false,data: data}); //未注册
                    }else{
                        let theuser = user.rows[0];
                        let token = {user: {id: theuser.id, username: theuser.username}, scopes: utils.getUserScopes(theuser), access_token: utils.uid(255), refresh_token: utils.uid(255)}; //生成token
                        log.debug(token);
                        redisClient.set(token.access_token, JSON.stringify(token), function(err) { //保存token到redis
                            redisClient.expire(token.access_token, settings.oauth_conf.tokenLife);
                            if (err) {
                                return res.send({success: false, data: "登录失败，请重试！"});
                            } else {
                                delete theuser.password; //删除密码属性
                                return res.send({
                                    success: true,
                                    info: {
                                        user: theuser,
                                        permissions: utils.getPermissions(theuser.role),
                                        access_token: token.access_token,
                                        refresh_token: token.refresh_token

                                    },
                                    signin: true,
                                    data: theuser
                                });
                            }
                        })
                        // res.send({success: true, signin: true,data: user.rows[0]}); //已注册
                    }
                });

            });
        }
    });
});

module.exports = router;

